//
//  NewsWebViewController.m
//  AnXin100
//
//  Created by Sakura on 2018/11/20.
//  Copyright © 2018 tzhg. All rights reserved.
//

#import "NewsWebViewController.h"
#import <WebKit/WebKit.h>
#import "WLCircleProgressView.h"
@interface NewsWebViewController ()<WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *mainWebView;

@property (nonatomic, strong) WLCircleProgressView *circleProgress;

@end

@implementation NewsWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.mainWebView];
    _circleProgress = [WLCircleProgressView viewWithFrame:CGRectMake(80, 80, 100, 100) circlesSize:CGRectMake(30, 5, 30, 5)];
    _circleProgress.layer.cornerRadius = 10;
    _circleProgress.progressValue = 0.2;
    _circleProgress.center = self.view.center;
    [self.view addSubview:_circleProgress];

}

// 懒加载
- (WKWebView *)mainWebView {
    if (!_mainWebView) {
        WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        webConfig.preferences = [[WKPreferences alloc] init];
        // 默认为0
        webConfig.preferences.minimumFontSize = 10;
        // 默认认为YES
        webConfig.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        // web内容处理池
//        webConfig.processPool = [[WKProcessPool alloc] init];
//        // 将所有cookie以document.cookie = 'key=value';形式进行拼接
//        DLog(@"token === %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"YYtoken"]);
//        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"YYtoken"];
//        NSLog(@"~~~%@", str);
//        NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = 'Authorization=Bearer %@';document.cookie = 'origin=%@'",[[NSUserDefaults standardUserDefaults] objectForKey:@"YYtoken"],@"YunyiApp"];
//
//        // 加cookie给h5识别，表明在ios端打开该地址
//        WKUserContentController* userContentController = WKUserContentController.new;
//        WKUserScript * cookieScript = [[WKUserScript alloc]
//                                       initWithSource: cookieValue
//                                       injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
//        [userContentController addUserScript:cookieScript];
//        [userContentController addScriptMessageHandler:self name:@"SwitchHospBack"];
//        [userContentController addScriptMessageHandler:self name:@"PicLitAdvisory"];
//
//        webConfig.userContentController = userContentController;
        
        _mainWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:webConfig];
        _mainWebView.navigationDelegate = self;
        _mainWebView.UIDelegate = self;
        _mainWebView.allowsBackForwardNavigationGestures = YES;
        [_mainWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_urlString]];
        [_mainWebView loadRequest:request];
    }
    return _mainWebView;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    ZX_WEAK_SELF
    if ([keyPath isEqual:@"estimatedProgress"] && object == _mainWebView) {
        [_circleProgress setAlpha:1.0f];
        _circleProgress.progressValue = _mainWebView.estimatedProgress;
        if (_mainWebView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [weakSelf.circleProgress setAlpha:0.0f];
            } completion:^(BOOL finished) {
                weakSelf.circleProgress.progressValue = 0.0f;
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

// 弹窗
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"网页导航加载完毕");
//    self.navigationController.navigationBarHidden = YES;
    self.title = webView.title;
    
}


@end
